package com.lw.yygh.user.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lw.yygh.helper.JwtHelper;
import com.lw.yygh.result.Result;
import com.lw.yygh.model.user.UserInfo;
import com.lw.yygh.user.service.UserInfoService;
import com.lw.yygh.user.utils.ConstantWxPropertiesUtils;
import com.lw.yygh.user.utils.HttpClientUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping("/api/ucenter/wx")
public class WeixinApiController {

    @Autowired
    private UserInfoService userInfoService;
    //返回微信二维码
    //返回生成二维码需要参数
    @GetMapping("/getLoginParam")
    @ResponseBody
    public Result genQrConnect() throws UnsupportedEncodingException {
        Map<String,Object> map=new HashMap<>();
        map.put( "appid", ConstantWxPropertiesUtils.WX_OPEN_APP_ID );
        map.put( "scope","snsapi_login" );
        String encode = URLEncoder.encode( ConstantWxPropertiesUtils.WX_OPEN_REDIRECT_URL, "utf-8" );
        //重定向地址需要url编码
        map.put( "redirect_uri",encode );
        map.put( "state",System.currentTimeMillis()+"" );
        return Result.ok( map );
    }

    //扫描二维码回调的接口
    @GetMapping("/callback")
    public String callback(String code, String state){
        //第一步，获取临时票据 code
        System.out.println("code"+code);
        //第二步，拿着code和微信id，请求微信固定地址，得到两个值
        StringBuffer baseAccessTokenUrl = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");
        String accessTokenUrl = String.format(baseAccessTokenUrl.toString(),
                ConstantWxPropertiesUtils.WX_OPEN_APP_ID,
                ConstantWxPropertiesUtils.WX_OPEN_APP_SECRET,
                code);
        //使用httpClient请求这个地址
        try {
            String accessTokenInfo = HttpClientUtils.get( accessTokenUrl );
            System.out.println(accessTokenInfo);
            //从返回的json字符串获取两个值access_token和openid
            JSONObject parseObject = JSONObject.parseObject( accessTokenInfo );
            String access_token = parseObject.getString( "access_token" );
            String openid = parseObject.getString( "openid" );
            //判断数据中是否存在微信扫描人的信息 根据openid判断
            UserInfo userInfo = userInfoService.getOne( new QueryWrapper<UserInfo>().eq( "openid", openid ) );
            if (userInfo==null){
                //第三步，使用获取的access_token和openid曲获取微信用户信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(baseUserInfoUrl, access_token, openid);
                String resultInfo = HttpClientUtils.get( userInfoUrl );
                System.out.println(resultInfo);
                JSONObject object = JSONObject.parseObject( resultInfo );
                //解析用户信息
                String nickname = object.getString( "nickname" );
                String headimgurl = object.getString( "headimgurl" );

                //将用户信息添加到数据库中
                userInfo=new UserInfo();
                userInfo.setNickName( nickname );
                userInfo.setOpenid( openid );
                userInfo.setAuthStatus( 0 );
                userInfoService.save( userInfo );
                userInfo.setStatus( 1 );
                userInfoService.updateById( userInfo );
            }
            //返回name和token
            Map<String, Object> map = new HashMap<>();
            String name = userInfo.getName();
            if(StringUtils.isEmpty(name)) {
                name = userInfo.getNickName();
            }
            if(StringUtils.isEmpty(name)) {
                name = userInfo.getPhone();
            }
            map.put("name", name);
            if(StringUtils.isEmpty(userInfo.getPhone())) {
                map.put("openid", userInfo.getOpenid());
            } else {
                map.put("openid", "");
            }
            String token = JwtHelper.createToken(userInfo.getId(), name);
            System.out.println(userInfo.getId());
            map.put("token", token);
            System.out.println("openid"+map.get("openid"));
            //跳转到前端页面中
            return
                    "redirect:" + ConstantWxPropertiesUtils.YYGH_BASE_URL +
                    "/weixin/callback?token="+map.get("token")+"&openid="+map.get("openid")+"&name="+URLEncoder.encode((String)map.get("name"));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


}
